<template>
  <div class="send-http-container">
    <div class="header">
      <h1>HTTP 调试工具</h1>
      <p>简单易用的 HTTP 请求调试工具：因为有跨域限制，实际请求通过 background 发送，会自动携带 cookie 等请求头</p>
      <el-button type="primary" @click="router.push('/history')">查看历史记录</el-button>
    </div>

    <div class="request-section">
      <el-card class="request-card">
        <template #header>
          <div class="card-header">
            <span>请求配置</span>
          </div>
        </template>

        <!-- URL 和方法选择 -->
        <div class="url-section">
          <el-row :gutter="20">
            <el-col :span="4">
              <el-select v-model="method" placeholder="方法">
                <el-option label="GET" value="GET"></el-option>
                <el-option label="POST" value="POST"></el-option>
                <el-option label="PUT" value="PUT"></el-option>
                <el-option label="DELETE" value="DELETE"></el-option>
                <el-option label="PATCH" value="PATCH"></el-option>
                <el-option label="HEAD" value="HEAD"></el-option>
                <el-option label="OPTIONS" value="OPTIONS"></el-option>
              </el-select>
            </el-col>
            <el-col :span="16">
              <el-input
                v-model="url"
                placeholder="请输入URL，例如：https://api.example.com/users"
                size="large"
              />
            </el-col>
            <el-col :span="4">
              <el-button 
                type="primary" 
                @click="sendRequest" 
                :loading="loading"
                size="large"
                style="width: 100%"
              >
                {{ loading ? '发送中...' : '发送请求' }}
              </el-button>
            </el-col>
          </el-row>
        </div>

        <!-- 请求头部 -->
        <div class="headers-section">
          <h3>请求头部 (Headers)</h3>
          <el-row :gutter="20" v-for="(header, index) in headersList" :key="index">
            <el-col :span="10">
              <el-input
                v-model="header.key"
                placeholder="Header 名称"
                size="small"
              />
            </el-col>
            <el-col :span="10">
              <el-input
                v-model="header.value"
                placeholder="Header 值"
                size="small"
              />
            </el-col>
            <el-col :span="4">
              <el-button 
                type="danger" 
                @click="removeHeader(index)"
                size="small"
                style="width: 100%"
              >
                删除
              </el-button>
            </el-col>
          </el-row>
          <el-button @click="addHeader" type="primary" plain size="small">
            添加 Header
          </el-button>
        </div>

        <!-- 请求体 -->
        <div class="body-section" v-if="['POST', 'PUT', 'PATCH'].includes(method)">
          <h3>请求体 (Body)</h3>
          <el-tabs v-model="bodyType">
            <el-tab-pane label="JSON" name="json">
              <el-input
                v-model="body"
                type="textarea"
                :rows="8"
                placeholder="输入JSON格式的请求体"
              />
            </el-tab-pane>
            <el-tab-pane label="原始文本" name="text">
              <el-input
                v-model="body"
                type="textarea"
                :rows="8"
                placeholder="输入原始文本"
              />
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-card>
    </div>

    <!-- 响应结果 -->
    <div class="response-section" v-if="response">
      <el-card class="response-card">
        <template #header>
          <div class="card-header">
            <span>响应结果</span>
            <el-tag 
              :type="getStatusType(response.status)"
              size="large"
            >
              {{ response.status }} {{ response.statusText }}
            </el-tag>
          </div>
        </template>

        <el-tabs v-model="responseTab">
          <el-tab-pane label="响应体" name="body">
            <div class="response-info">
              <p><strong>响应时间：</strong> {{ responseTime }}ms</p>
              <p><strong>内容类型：</strong> {{ response.headers['content-type'] || 'N/A' }}</p>
            </div>
            <el-input
              v-model="formattedResponse"
              type="textarea"
              :rows="15"
              readonly
              class="response-body"
            />
          </el-tab-pane>
          <el-tab-pane label="响应头" name="headers">
            <div class="response-headers">
              <div v-for="(value, key) in response.headers" :key="key" class="header-item">
                <strong>{{ key }}:</strong> {{ value }}
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>

    <!-- 错误提示 -->
    <div v-if="error" class="error-section">
      <el-alert
        :title="error.title"
        :description="error.message"
        type="error"
        show-icon
        @close="clearError"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'

const router = useRouter()
const route = useRoute()

const url = ref('')
const method = ref('GET')
const headersList = ref([{ key: 'Content-Type', value: 'application/json' }])
const body = ref('')
const bodyType = ref('json')
const response = ref(null)
const responseTab = ref('body')
const loading = ref(false)
const error = ref(null)
const responseTime = ref(0)

// 格式化响应数据
const formattedResponse = computed(() => {
  if (!response.value) return ''
  
  try {
    if (typeof response.value.data === 'object') {
      return JSON.stringify(response.value.data, null, 2)
    } else {
      return response.value.data
    }
  } catch (e) {
    return response.value.data
  }
})

// 添加请求头
const addHeader = () => {
  headersList.value.push({ key: '', value: '' })
}

// 删除请求头
const removeHeader = (index) => {
  headersList.value.splice(index, 1)
}

// 清除错误
const clearError = () => {
  error.value = null
}

// 根据状态码获取标签类型
const getStatusType = (status) => {
  if (status >= 200 && status < 300) return 'success'
  if (status >= 300 && status < 400) return 'info'
  if (status >= 400 && status < 500) return 'warning'
  return 'danger'
}

// 生成唯一ID
const generateId = () => {
  return Date.now().toString(36) + Math.random().toString(36).substr(2)
}

// 保存历史记录
const saveToHistory = async (requestData, responseData) => {
  try {
    const historyItem = {
      id: generateId(),
      url: requestData.url,
      method: requestData.method,
      headers: requestData.headers,
      body: requestData.body,
      status: responseData.status,
      statusText: responseData.statusText,
      responseTime: responseData.responseTime,
      timestamp: new Date().toISOString(),
      response: responseData
    }

    // 获取现有历史记录
    const result = await new Promise((resolve) => {
      chrome.storage.local.get(['httpHistory'], (result) => {
        resolve(result.httpHistory || [])
      })
    })

    // 添加新记录到开头，限制最多保存 100 条
    const updatedHistory = [historyItem, ...result].slice(0, 100)

    // 保存到 storage
    await new Promise((resolve) => {
      chrome.storage.local.set({ httpHistory: updatedHistory }, () => {
        resolve()
      })
    })
  } catch (error) {
    console.error('保存历史记录失败：', error)
  }
}



// 从 URL 参数恢复请求
const restoreFromQuery = () => {
  if (route.query.url) {
    url.value = route.query.url
  }
  if (route.query.method) {
    method.value = route.query.method
  }
  if (route.query.headers) {
    try {
      const headers = JSON.parse(route.query.headers)
      headersList.value = Object.entries(headers).map(([key, value]) => ({ key, value }))
    } catch (e) {
      console.error('解析 headers 失败：', e)
    }
  }
  if (route.query.body) {
    body.value = route.query.body
  }
}

// 发送 HTTP 请求
const sendRequest = async () => {
  if (!url.value.trim()) {
    error.value = {
      title: '请求错误',
      message: '请输入有效的 URL'
    }
    return
  }

  loading.value = true
  error.value = null
  response.value = null

  try {
    // 构建请求头
    const headers = {}
    headersList.value.forEach(header => {
      if (header.key && header.value) {
        headers[header.key] = header.value
      }
    })

    // 构建请求体
    let requestBody = null
    if (['POST', 'PUT', 'PATCH'].includes(method.value) && body.value) {
      try {
        // 尝试解析 JSON
        if (bodyType.value === 'json' && body.value.trim()) {
          requestBody = JSON.parse(body.value)
        } else {
          requestBody = body.value
        }
      } catch (e) {
        // 如果 JSON 解析失败，使用原始文本
        requestBody = body.value
      }
    }

    // 构建请求数据
    const requestData = {
      url: url.value,
      method: method.value.toUpperCase(),
      headers: headers,
      body: requestBody,
      timeout: 30000 // 30 秒超时
    }

    // 通过 background script 发送请求
    const result = await new Promise((resolve, reject) => {
      chrome.runtime.sendMessage(
        {
          action: 'sendHttpRequest',
          data: requestData
        },
        (response) => {
          if (chrome.runtime.lastError) {
            reject(new Error(chrome.runtime.lastError.message))
          } else if (response.success) {
            resolve(response.data)
          } else {
            reject(new Error(response.error))
          }
        }
      )
    })

    // 设置响应时间
    responseTime.value = result.responseTime

    // 构建响应对象，保持与 axios 格式一致
    response.value = {
      status: result.status,
      statusText: result.statusText,
      headers: result.headers,
      data: result.data,
      config: requestData,
      request: {}
    }

    // 保存到历史记录
    await saveToHistory(requestData, result)

  } catch (err) {
    // 处理错误
    error.value = {
      title: '请求错误',
      message: err.message || '发生未知错误'
    }
  } finally {
    loading.value = false
  }
}

// 组件挂载时恢复请求
onMounted(() => {
  restoreFromQuery()
})
</script>

<style scoped>
.send-http-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.header {
  text-align: center;
  margin-bottom: 30px;
}

.header h1 {
  color: #303133;
  margin-bottom: 10px;
}

.header p {
  color: #606266;
  font-size: 14px;
}

.request-section {
  margin-bottom: 30px;
}

.request-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
}

.url-section {
  margin-bottom: 25px;
}

.headers-section {
  margin-bottom: 25px;
}

.headers-section h3 {
  margin-bottom: 15px;
  color: #303133;
  font-size: 16px;
}

.headers-section .el-row {
  margin-bottom: 10px;
}

.body-section {
  margin-bottom: 20px;
}

.body-section h3 {
  margin-bottom: 15px;
  color: #303133;
  font-size: 16px;
}

.response-section {
  margin-bottom: 30px;
}

.response-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.response-info {
  margin-bottom: 15px;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
}

.response-info p {
  margin: 5px 0;
  color: #606266;
}

.response-body {
  font-family: 'Courier New', monospace;
}

.response-headers {
  max-height: 400px;
  overflow-y: auto;
}

.header-item {
  padding: 8px 0;
  border-bottom: 1px solid #ebeef5;
  color: #606266;
}

.header-item:last-child {
  border-bottom: none;
}

.error-section {
  margin-bottom: 30px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .send-http-container {
    padding: 10px;
  }
  
  .url-section .el-col {
    margin-bottom: 10px;
  }
}
</style>